<template>
  <div class="mian">
   <div class="mainMenu">
        <div class="head">
          <div>主菜单列表(master):</div>
        </div>
        <div class="menuList tree" :style="menuHeightStyles">
          <el-tree class="filter-tree" :data="menuTreeData" :default-checked-keys="checkedKeys" :expand-on-click-node="false" check-strictly
              node-key="id" :highlight-current="true" :props="defaultProps" ref="menuTree"
              :filter-node-method="filterNode" default-expand-all >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>
                  {{ node.label }}
                  <el-button type="text"  size="mini" icon="el-icon-plus" @click="addTenant( node, data)" class="el-button-add-tenant" :title="node.label">添加至租户</el-button>
                </span>
                <span>
                  <el-tag :type="data.client == 'web' ? 'success' : ''">{{ data.client + '端' }}</el-tag>
                  <el-tag :type="data.type=='0'?'success' :data.type=='1'?'' : 'warning'">{{ data.type=='0'?'菜单' :data.type=='1'?'按钮' : '接口'}}</el-tag>
                </span>
              </span>
            </el-tree>
        </div>
   </div>
   <div class="tenantMenu">
      <div class="head">
        <div>租户菜单列表(tenement):</div>
        <el-select   v-model="currTenantId"  filterable clearable size="mini" style="width:180px" @change="tenantChange" placeholder="请选择租户">
          <el-option  v-for="item in tenantList"   style="width: 100%" :key="item.tenantId" :label="item.name" :value="item.tenantId">
            </el-option>
        </el-select>
        <div>
          <el-button type="info" :loading="syncButtonLoading"  icon="el-icon-position" plain size="mini" @click="syncMenu">同步菜单</el-button>
          <el-button type="primary" :loading="saveButtonLoading"  icon="el-icon-check" plain size="mini" @click="saveTenement">保存更改</el-button>
        </div>
      </div>
      <div class="menuList tree"  :style="menuHeightStyles">
        <el-tree class="filter-tree" :data="tenantTreeData" :default-checked-keys="checkedKeys" :expand-on-click-node="false" check-strictly
              node-key="id" :highlight-current="true" :props="defaultProps" ref="tenantTree"
              :filter-node-method="filterNode"  :default-expanded-keys="tenantTreeExpanded" @node-expand="tenantNodeExpand" @node-collapse="tenantNodeCollapse">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>
                  {{ node.label }}
                  <el-button type="text"  size="mini" icon="el-icon-delete" @click="delTenant( node, data)" class="el-button-move-tenant" :title="node.label">从租户移除</el-button>
                </span>
                <span>
                  <el-tag :type="data.client == 'web' ? 'success' : ''">{{ data.client + '端' }}</el-tag>
                  <el-tag :type="data.type=='0'?'success' :data.type=='1'?'' : 'warning'">{{ data.type=='0'?'菜单' :data.type=='1'?'按钮' : '接口'}}</el-tag>
                </span>
              </span>
            </el-tree>
      </div>
   </div>
  </div>
</template>
<script>
//import { selectPermissionBygolab,synchronousPermission,selectPermissionBytenant,deletePermissionBytenant,tenantUserList,getMenuById} from "@/api/tenantPermission";
export default {
  components: {  },
  name: "tenantPermission",
  data() {
    return {
      //当前选中租户
      currTenantId:'',
      oldTenantId:'',
      //租户数据
      tenantList:[],
      //主菜单树
      menuTreeData:[],
      //租户菜单树
      tenantTreeData:[],
      tenantTreeExpanded:[],
      checkedKeys: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      menuHeight:'500px',
      saveButtonLoading:false,
      syncButtonLoading:false,
    };
  },
  computed: {
    menuHeightStyles() {
      return {
        height: this.menuHeight
      };
    }
  },
  created() {
    this.getGenantUserList()
    this.getMenu()
  },
  mounted() {
      this.$nextTick(() => {
          this.setHeight()
      })
      window.onresize = () => {
          return (() => {
              this.$nextTick(() => {
                  this.setHeight()
              })
          })()
      }
  },
  methods: {
    //同步菜单
    syncMenu(){
      if(!this.currTenantId){
        this.$message.warning('请先选择租户');
        return
      }
      this.syncButtonLoading = true
      setTimeout(()=>{
        this.$message.success('同步菜单成功');
        this.syncButtonLoading = false
      },1000)
    },
    //保存更改
    saveTenement(){
      if(!this.currTenantId){
        this.$message.warning('请先选择租户');
        return
      }
      this.saveButtonLoading = true
      let tObj =  JSON.parse(window.sessionStorage.getItem('tenantPermission-tenantTreeData'))
      tObj[this.currTenantId] = this.tenantTreeData
      window.sessionStorage.setItem('tenantPermission-tenantTreeData',JSON.stringify(tObj))
      setTimeout(()=>{
        this.$message.success('保存成功');
        this.saveButtonLoading = false
      },1000)
    },
    //从租户移除
    delTenant(node,data){
      if(data.parentId == -1){
        let k = -1
        this.tenantTreeData.forEach((v,index)=>{
          if(v.id == data.id){
            k = index
          }
        })
        if(k!=-1){
          this.tenantTreeData.splice(k,1)
        }
      }else{
        this.deleteNode(this.tenantTreeData,data.id)
      }
    },
    //租户移除删除节点
    deleteNode(treeData, nodeId) {
      function deleteNodeRecursive(nodes, nodeId) {
        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].id === nodeId) {
            nodes.splice(i, 1);
            return true;
          }
          if (nodes[i].children && deleteNodeRecursive(nodes[i].children, nodeId)) {
            if (nodes[i].children.length === 0) {
              nodes.splice(i, 1);
            }
            return true;
          }
        }
        return false;
      }
      const wasDeleted = deleteNodeRecursive(treeData, nodeId);
      return wasDeleted ? treeData : null; 
    },
    //租户节点展开
    tenantNodeExpand(val,node,data){
      if(!this.tenantTreeExpanded.includes(val.id)){
        this.tenantTreeExpanded.push(val.id)
      }
    },
    //租户节点关闭
    tenantNodeCollapse(val,node,data){
      let k = this.tenantTreeExpanded.indexOf(val.id)
      if(k != -1){
        this.tenantTreeExpanded.splice(k,1)
      }
    },
    //添加至租户关闭
    addTenant(node,data){
      if(!this.currTenantId){
        this.$message.warning('请先选择租户');
        return
      }
      this.constructTenantTree(data)
    },
    //添加至租户生成新树
    constructTenantTree(data){
      if(data.parentId == -1){
        let list1 = this.treeToArray(JSON.parse(JSON.stringify([data])))
        let list2 = this.treeToArray(JSON.parse(JSON.stringify(this.tenantTreeData)))
        let arr = this.uniqueByKey(list2.concat(list1),'id').sort(this.sortBy('id'))
        this.$nextTick(()=>{
          this.tenantTreeData = this.arrayToTree(arr)
          this.$forceUpdate()
          this.tenantTreeExpanded.push(data.id)
        })
      }else{
        let list = this.getAllParentNodes(JSON.parse(JSON.stringify(this.menuTreeData)),data.parentId)
        for(let i=0;i<list.length;i++){
          list[i].children = undefined
          this.tenantTreeExpanded.push(list[i].id)
        }
        let list2 = this.treeToArray(JSON.parse(JSON.stringify(this.tenantTreeData)))
        let arr = this.uniqueByKey(list2.concat(list,[data]),'id').sort(this.sortBy('id'))
        this.$nextTick(()=>{
          this.tenantTreeData = this.arrayToTree(arr)
          this.$forceUpdate()
        })
      }
    },
    //列表转换成树
    arrayToTree(array, parentId = -1) {
      let tree = []
      for (let item of array) {
        if (item.parentId === parentId) {
          let children = this.arrayToTree(array, item.id)
          if (children.length) {
            item.children = children
          }
          tree.push(item)
        }
      }
      return tree
    },
    //树转换成列表
    treeToArray(tree) {
      let result = [];
      function traverse(node) {
        const newNode = { ...node };
        delete newNode.children;
        result.push(newNode);
        if (node.children) {
          node.children.forEach(traverse);
        }
      }
      tree.forEach(traverse);
      return result;
    },
    //获取节点所有父级
    getAllParentNodes(list, id) {
      for(let i in list) {
        if(list[i].parentId == id) {
          return [list[i]].filter(v => v.parentId != id)
        }
        if(list[i].children?.length > 0) {
          let node = this.getAllParentNodes(list[i].children, id)
          if(node) return node.concat(list[i]).filter(v => v.parentId != id)
        }
      }
    },
     // 点击编辑
    clickEdit(val, node, tree) {
    },
    //拖拽节点
    handleDrop(node, dropNode, dropType, ev) {
      let menuId = node.data.id; // 被拖拽节点id
      let parentId = null;
      if (dropType === 'inner') {
        parentId = dropNode.data.id;
      } else {
        parentId = dropNode.data.parentId
      }
    },
    filterNode(value, data) { 
      if (!value) return true;
      return data.label && data.label.indexOf(value) !== -1;
    },
    //获取主菜单列表
    async getMenu(){
      let tree =  JSON.parse(window.sessionStorage.getItem('tenantPermission-menuTreeData')) 
      if(tree && tree.length){
        this.$nextTick(()=>{
          this.menuTreeData = [].concat(tree)
          this.$forceUpdate()
          this.setMockTenant()
        })
      }else{
       /* let res = await getMenuById()
        console.log("menuTreeData:",res)
        this.$nextTick(()=>{
          this.menuTreeData = [].concat(res.data)
          this.$forceUpdate()
          window.sessionStorage.setItem('tenantPermission-menuTreeData',JSON.stringify(this.menuTreeData))
        })*/
      }
    },
    //模拟租户菜单
    setMockTenant(){
      let tObj =  JSON.parse(window.sessionStorage.getItem('tenantPermission-tenantTreeData'))
      if(!tObj){
        let tenantTreeData = {}
        let k = this.menuTreeData.length
        this.tenantList.forEach((v)=>{
          tenantTreeData[v.tenantId] = [this.menuTreeData[Math.floor(Math.random() * (k - 0 + 1))] ]
        })
        window.sessionStorage.setItem('tenantPermission-tenantTreeData',JSON.stringify(tenantTreeData))
      }
    },
    //选择租户
    tenantChange(v){
      /*selectPermissionBytenant({
        tenantId:v
      }).then((res) => {
        
      });*/
      if(v == this.oldTenantId){
        return
      }else{
        this.oldTenantId = v
      }
      let tObj =  JSON.parse(window.sessionStorage.getItem('tenantPermission-tenantTreeData'))
      this.tenantTreeExpanded = []
      this.$nextTick(()=>{
          this.tenantTreeData = tObj[v]
          this.$forceUpdate()
        })
    },
    //获取租户
    getGenantUserList(){
      let list =  JSON.parse(window.sessionStorage.getItem('tenantPermission-tenantList')) 
      if(list && list.length){
        this.tenantList = list
      }else{
       /* let res = await  tenantUserList({
          currentPage: 1,
          pageSize: 1000,
        })
        if (res.data.code == 0) {
            this.tenantList = res.data.data.records;
            window.sessionStorage.setItem('tenantPermission-tenantList',JSON.stringify(this.tenantList))
        }*/
      }
    },
    sortBy (field) {
      return (x, y) => {
        return x[field] - y[field]
      }
    },
    uniqueByKey(arr, key) {
      const map = arr.reduce((acc, obj) => {
        const keyValue = obj[key];
        acc[keyValue] = obj;
        return acc;
      }, {});
      return Object.values(map);
    },
    setHeight() {
          var clientHeight = 0;
          if (document.body.clientHeight && document.documentElement.clientHeight) {
              clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
          } else {
              clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
          }
          this.menuHeight = ((clientHeight ? clientHeight : 900)  ) + 'px'
      },
  },
};
</script>
<style lang="scss" scoped>
@import './scss/index.scss';
</style>
